package elitequant.util;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import elitequant.event.ClientMq;

/**
 * https://sourceforge.net/projects/sigar/?source=typ_redirect
 * 
 * http://blog.csdn.net/a123demi/article/details/50689265
 */
public final class OsInfo {
    
    static {

        String path = ClientMq.class.getResource("/elitequant/server").getPath();
        
        path = path.replaceFirst("/", "");
        path = path.replaceAll("%20", " ");
        System.setProperty("org.hyperic.sigar.path", path);
    }
    
    private final static Sigar sigar = new Sigar();

    /**
     * 获取JVM 的CPU占用率（%）
     * 
     * @return
     */
    public static String getCPURate() {
        String cpuRate = "";
        try {
            CpuPerc[] cpuPercs = sigar.getCpuPercList();
            double temp = 0;
            for(CpuPerc cp : cpuPercs) {
                temp += cp.getCombined();
            }
            temp = temp / cpuPercs.length;
            if(!Double.isNaN(temp)) {
                cpuRate = String.format("%.2f", temp);
            }
        } catch (Exception e) {
            // ignore
        }
        return cpuRate;
    }

    /**
     * 获取JVM的内存占用率（%）
     * 
     * @return
     */
    public static String getMemoryRate() {
//        long total = Runtime.getRuntime().totalMemory();
//        long free = Runtime.getRuntime().freeMemory();
//        float rate = (total - free)/(float)total;
//        return  String.format("%.2f", rate);
        String memRate = "";
        try {
            Mem mem = sigar.getMem();
            double temp = mem.getActualUsed()/(float)mem.getTotal();
            if(!Double.isNaN(temp)) {
                memRate = String.format("%.2f", temp);
            }
        } catch (Exception e) {
            // ignore
        }
        return memRate;
    }

}
